/*
 * GStackTraceUtil.java
 * Created on 22 déc. 2007
 *
 * Glacéo Internet Platform
 * http://sourceforge.net/projects/chm/
 *
 * Copyright (c) 2005-2007, Jan Janke (VirtualHockey Project)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hockeo.vhbase.utils.lang;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Utility methods to get an exception's stacktrace as a string.
 *
 * @version $Id$
 * @author jjanke
 */
public final class GStackTraceUtil
{
  /**
   * Private constructor to avoid instantiation.
   */
  private GStackTraceUtil()
  {}

  /**
   * Returns the stacktrace of the passed throwable as string.
   *
   * @param throwable the Throwable for which to transform the stacktrace
   * @return the stacktrace written by {@link Throwable#printStackTrace()} as string
   */
  public static String getStackTrace( Throwable throwable )
  {
    final StringWriter result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter( result );

    throwable.printStackTrace( printWriter );

    return result.toString();
  }

  /**
   * Returns the stacktrace of the given throwable as a formatted string.
   *
   * @param throwable the Throwable for which to transform the stacktrace
   * @param strNewLine the new line character to be used when splitting the stacktrace into lines
   * @return the stacktrace written by {@link Throwable#printStackTrace()} as string
   */
  public static String getCustomStackTrace( Throwable throwable, String strNewLine )
  {
    // add the class name and any message passed to constructor
    //
    final StringBuilder result = new StringBuilder( "Exception: " );
    result.append( throwable.toString() );
    result.append( strNewLine );
    result.append( strNewLine );

    // add each element of the stack trace
    //
    for ( StackTraceElement element : throwable.getStackTrace() )
    {
      result.append( element );
      result.append( strNewLine );
    }

    return result.toString();
  }
}
